`

generating a massive amount of noise in your terminal in cases when

your script is large and contains a specific problem area.

Basic Syntax

At this point, you’ve written a two-line script that prints the

message Hello World! to the screen. You’ve also learned how to run

and debug a script. Now you’ll learn some bash syntax so you can

write more useful scripts.

The most basic bash scripts are just lists of Linux commands

collected in a single file. For example, you could write a script that

creates resources on a system and then prints information about these

resources to the screen (Listing 1-8).

#!/bin/bash

# All this script does is create a directory, create a file

# within the directory, and then list the content of the directory.

mkdir directory

touch mydirectory/myfile

ls -l mydirectory

Listing 1-8

A basic bash script

In this example, we use mkdir to create a directory named

mydirectory. Next, we use the touch command to create a file

named myfile within the directory. Lastly, we run the ls -l

command to list the contents of the mydirectory directory.

The output of the script looks as follows:

--snip--

-rw-r--r-- 1 user user 0 Feb 16 13:37 myfile

However, this line-by-line strategy could be improved in several

ways. First, when a command runs, bash waits until it finishes before

advancing to the next line. This means that if you include a long-

running command (such as a file download or large file copy),

remaining commands won’t be executed until that command has

completed. We also have yet to implement any checks to validate

that all commands have executed correctly. You’ll need to write

more intelligent programs to reduce errors during runtime.

Writing sophisticated programs often requires using features like

variables, conditions, loops, tests, and so on. For example, what if

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks